layui.config({
    base: config.base + 'layui-admin/'
}).extend({
    index: 'lib/index'
    , tagsInput: 'tagsInput/tagsInput'
}).use(['index', 'tagsInput'], function () {
    const $ = layui.$;
    const admin = layui.admin;
    const layer = layui.layer;
    const table = layui.table;
    const element = layui.element;
    const form = layui.form;
    const tagsInput = layui.tagsInput;
    const laytpl = layui.laytpl;
    const layedit = layui.layedit;
    layedit.build('content', {height: 200, uploadImage: {url: '../../admin/oss/upload'}});

    const fn = {
        editor: null
        , dump: function (item) {
            $('#id').val(0);
            if (item) {
                form.val('notice-form', item);//表单赋值
            } else {
                $('#notice-form')[0].reset();//清空表单
            }
        }
        //查询
        , query: function (statusId) {
            tableRender.reload({
                where: {statusId: statusId}
                , page: {curr: 1}
                , done: function (data) {
                    if (statusId === 0) {
                        fn.unread(data.total || 0);
                    }
                }
            });
        }
        //打开编辑窗口
        , edit: function (item) {
            fn.dump(item);
            admin.popup({
                type: 1
                , title: (item) ? '公告编辑' : '公告添加'
                , area: '100'
                , content: $('#notice-form')
                , btn: ['确定', '取消']
                , yes: function (index) {
                    //绑定用户编辑数据提交
                    form.on('submit(notice-submit)', function (data) {
                        data.field.content = layedit.getContent(fn.editor);
                        fn.save(data.field, function () {
                            layer.close(index);
                        });
                    });
                    $('#notice-submit').trigger('click');
                }
                , success: function () {
                    fn.editor = layedit.build('content', {height: 200, uploadImage: {url: '../../admin/oss/upload'}});
                    $('#receiveUser').importTags((item) ? item.receiveUser : '');
                    $('#receiveUser').tagsInput({
                        defaultText: '+用户（支持用户名/邮箱/手机号）'
                        , skin: 'tagsinput-default'
                        , onAddTag: function (tag) {
                            admin.req({
                                url: '../../admin/user/show.json'
                                , data: {username: tag}
                                , success: function (data) {
                                    if (data.success) {
                                        if ($('#receiveUser').val().split(',').length > 1) {
                                            layer.msg('只能选择一个用户！');
                                            $('#receiveUser').removeTag(tag);
                                        }
                                    } else {
                                        $('#receiveUser').removeTag(tag);
                                    }
                                }
                                , error: function () {
                                    $('#receiveUser').removeTag(tag);
                                }
                            });
                        }
                    });
                }
            });
        }
        //删除
        , del: function (item) {
            layer.confirm('是否删除【' + item.title + '】通知公告？', {
                title: '删除'
                , icon: 3
                , closeBtn: 0
                , skin: 'layui-layer-admin'
            }, function (index) {
                layer.close(index);
                admin.req({
                    url: '../../admin/notice/delete.json'
                    , type: 'delete'
                    , data: {id: item.id}
                    , done: function (data) {
                        tableRender.reload();
                    }
                });
            });
        }
        //保存（POST：添加；PUT：修改）
        , save: function (data, fn) {
            admin.req({
                url: '../../admin/notice/' + ((data.id === '0') ? 'save.json' : 'edit.json')
                , contentType: "application/json;charset=UTF-8"
                , type: (data.id === '0') ? 'post' : 'put'
                , data: JSON.stringify(data)
                , done: function (data) {
                    tableRender.reload();
                    typeof fn === 'function' && fn();
                }
            });
        }
        , show: function (item) {
            admin.req({
                url: '../../admin/notice/show.json',
                data: {id: item.id},
                done: function (data) {
                    laytpl($('#notice-tpl').html()).render(data.data, function (html) {
                        $('#notice-show').html(html).show();
                        $('#notice-list').hide();
                        $('#notice-back').on('click', function () {
                            $('#notice-list').show();
                            $('#notice-show').hide();
                        });
                    });
                    tableRender.reload();
                    admin.req({
                        url: '../../admin/notice/list.json',
                        data: {statusId: 0, page: 1, offset: 0, limit: 10},
                        done: function (data) {
                            fn.unread(data.total || 0);
                        }
                    });
                }
            });
        }
        , unread: function (total) {
            if (total > 0) {
                $('#notice-unread').addClass('layui-badge').text(total > 99 ? '99+' : total);
                parent.layui.$('#notice-unread').addClass('layui-badge').text(total > 99 ? '99+' : total);
            } else {
                $('#notice-unread').removeClass('layui-badge').text('');
                parent.layui.$('#notice-unread').removeClass('layui-badge').text('');
            }
        }
    };
    const tableRender = table.render({
        id: 'notice-table'
        , elem: '#notice-table'
        , toolbar: '#notice-toolbar'
        , url: '../../admin/notice/list.json'
        , where: {statusId: 0}
        , page: true
        , response: {
            statusName: 'code'
            , statusCode: 0
            , msgName: 'message'
            , countName: 'total'
            , dataName: 'data'
        }
        , cols: [
            [
                {type: 'radio'}
                , {field: 'title', title: '标题', templet: '#title-tpl'}
                , {field: 'statusId', title: '状态', align: 'center', width: 80, templet: '#status-tpl'}
                , {field: 'receiveUser', title: '接收用户', width: 90, templet: '#receive-tpl'}
                , {field: 'createUser', title: '发送用户', width: 90}
                , {field: 'createTime', title: '发送时间', width: 120}
                , {field: 'updateUser', title: '修改用户', width: 100, hide: true}
                , {field: 'updateTime', title: '修改时间', width: 120, hide: true}
            ]
        ]
        , done: function (data) {
            if (tableRender.config.where.statusId === 0) {
                if ((data.total || 0) === 0) {
                    element.tabChange('notice-tab', 'all');
                }
                fn.unread(data.total || 0);
            }
        }
    });
    //绑定工具栏事件
    table.on('toolbar(notice-table)', function (obj) {
        const items = table.checkStatus('notice-table').data;
        if (obj.event === 'add-toolbar') {
            fn.edit();
        } else if (obj.event === 'edit-toolbar' || obj.event === 'del-toolbar') {
            if (items.length <= 0) {
                layer.msg("请选择一条纪录！");
            } else {
                if (obj.event === 'edit-toolbar') {
                    fn.edit(items[0]);
                } else if (obj.event === 'del-toolbar') {
                    fn.del(items[0]);
                }
            }
        }
    });
    //绑定表格数据行操作事件
    table.on('tool(notice-table)', function (obj) {
        const item = obj.data;
        if (obj.event === 'show-tool') {
            fn.show(item);
        }
    });
    element.on('tab(notice-tab)', function (elem) {
        if (elem.index === 0 || elem.index === 1) {
            fn.query(elem.index);
        } else {
            fn.query(null);
        }
    });
});